import React, { useEffect, useState, useCallback } from 'react';

import basicRoute from '@/router'
import { createBrowserRouter, RouterProvider } from "react-router-dom";
import { joinRoutes, getInitUser, transRouteTree, getMenuTree } from '@/router/helper.tsx';

import { MenuRoute } from '@/router/types';

import { MenuContext } from '@/router/menuContext'
import { getRouters } from '@/api/menu'

import { useTranslation } from 'react-i18next';

const App = () => {
  const { t } = useTranslation();
  const [loading, setLoading] = useState(true)
  const [realRouter, setRealRouter] = useState(createBrowserRouter(joinRoutes(basicRoute)))
  const [memuList, setMemuList] = useState<MenuRoute>({path: '/', routes: []})

  const init = useCallback(async (skipCheck: boolean = false) => {
    if(skipCheck || await getInitUser()) {
      const {data: serverRouter, success} = await getRouters()
      if (!success) return false
      const routeData = transRouteTree(serverRouter.data)
      setRealRouter(createBrowserRouter(joinRoutes(routeData)))
      setMemuList(getMenuTree(serverRouter.data))
    }
    setLoading(false)
  }, [])

  // 登陆信息获取以及空白页面拦截
  useEffect(() => {
    setLoading(true);
    init()
  }, [])

  if(loading) return null
  
  return (
    <MenuContext.Provider value={{memuList, reload: init,}}>
      <RouterProvider router={realRouter} fallbackElement={<p>...</p>} />
    </MenuContext.Provider>
  );
};

export default App